<?php

class FormAction_Form extends FormAction
{

  /**
   *
   * @var IValidator
   */
  public $rules = null;

  protected $template = 'form';

  public function execute()
  {
    $this->loadData();

    if ($this->hasPostData()) {
      $this->setDataFromPost();
      $this->validate();
      $this->save();

      return true;
    }

    return false;
  }

  public function render()
  {
    return parent::render();
  }

  protected function save()
  {
    foreach ($this->formData as &$row) {
      $this->gateway()->save($row);
    }
  }

  protected function validate()
  {
    $this->rules = DataValidator::parseFrom($this->rules);

    foreach ($this->formData as $row) {
      $this->rules->validate($row);

      $elements = $this->form->getElements($this->action);
      while ($element = $elements->next()) {
        $element->validate($row);
      }
    }
  }

  protected function loadData()
  {
    $this->formData = array();

    foreach ((array) $this->form->getId() as $id) {
      $params = array();

      $params['fields'] = array($this->form->pk);
      $params['where'] = array();
      $params['data'] = array();

      foreach ($this->form->getFilters() as $filter) {
        $filter->injectQueryParams($params);
      }

      $elements = $this->form->getElements($this->action);
      while ($element = $elements->next()) {
        $element->injectQueryParams($params);
      }

      $params['fields'] = array_filter(array_unique($params['fields']));

      $row = $this->gateway()->find($id, $params);

      $this->filterDbData($row, $this->action);

      if (is_null($row)) {
        throw new Exception("Record not found");
      }

      $this->formData[] = &$row;
    }
  }

}
